<template>
  <div class="container">
    <topTitle
      :titleText="titleText"
      :back="back"
      @gobackTriser="goBack"
    ></topTitle>
    <div class="mainCon noTitleExplain">
      <el-form
        :model="formData"
        label-width="164px"
        :rules="formRules"
        ref="formData"
        class="form"
      >
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="用户名：" prop="username">
              <el-input
                class="mWidth"
                v-model="formData.username"
                placeholder="建议使用姓名拼音+数字组合"
                :disabled="type == 'edit'"
                @blur="formData.username = changeValue($event)"
              ></el-input>
              <div style="color: #606266; font-size: 12px; line-height: 20px">
                比如账号使用人真实姓名:张三,用户名可填:zhangsan123
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="登录密码：" prop="password">
              <el-input
                class="mWidth"
                v-if="type == 'edit'"
                v-model="formData.password"
                placeholder="请输入"
                @blur="formData.password = changeValue($event)"
                type="password"
              ></el-input>
              <el-input
                class="mWidth"
                v-else
                v-model="formData.password"
                placeholder="请输入"
                @blur="formData.password = changeValue($event)"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="姓名：" prop="nickname">
              <el-input
                class="sWidth"
                v-model="formData.nickname"
                placeholder="建议输入真实姓名"
                @blur="formData.nickname = changeValue($event)"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="手机号：" prop="tel">
              <el-input
                class="sWidth"
                v-model="formData.tel"
                placeholder="请输入，可用于找回和修改密码"
                @blur="formData.tel = changeValue($event)"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="账号状态：" prop="enabled">
              <el-select
                class="xsWidth"
                v-model="formData.enabled"
                clearable
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) of enabledData"
                  :key="index"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
              <!-- <el-input v-model="formData.ruleName" placeholder="请输入，可用于找回和修改密码" @blur="formData.ruleName = changeValue($event)"></el-input> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="归属公司：">
              <span v-if="loginType == 'company'">本公司（施工方）</span>
              <el-radio-group v-else v-model="ownerShip" @change="changeOwner">
                <el-row style="height: 36px; line-height: 44px">
                  <el-radio label="1">本公司(施工方)</el-radio>
                  <el-radio label="2">劳务公司</el-radio>
                </el-row>
                <el-row v-if="ownerShip == '2'">
                  <el-form-item prop="uscc">
                    <el-select
                      clearable
                      filterable
                      placeholder="请选择"
                      v-model="formData.uscc"
                      class="mWidth"
                    >
                      <el-option
                        v-for="item in unitArr"
                        :key="item.uscc"
                        :label="item.companyName"
                        :value="item.uscc"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-row>
              </el-radio-group>
              <!-- <el-input v-model="formData.ruleName" placeholder="请输入，可用于找回和修改密码" @blur="formData.ruleName = changeValue($event)"></el-input> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="岗位：" prop="roleCode">
              <el-radio-group v-model="formData.roleCode">
                <el-row style="height: 36px; line-height: 44px">
                  <el-radio
                    :label="item.code"
                    v-for="(item, index) of filterRoleList"
                    :key="index"
                    >{{ item.name }}
                    <el-tooltip
                      :content="item.remark"
                      placement="top"
                      effect="dark"
                    >
                      <i class="icon iconfont iconhuabanfuben"></i>
                    </el-tooltip>
                  </el-radio>
                </el-row>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom" v-if="loginType == 'company'">
          <el-col :span="24" class="col-position">
            <el-form-item label="管辖项目：" prop="userProjectJson">
              <el-select
                class="mWidth"
                v-model="formData.userProjectJson"
                clearable
                filterable
                placeholder="请选择要授权的管辖项目"
                @change="selectValue"
              >
                <el-option
                  v-for="(item, index) in projectList"
                  :key="index"
                  :label="item.projectName"
                  :value="item.projectId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom" style="margin-top: 18px">
          <el-col :span="24" class="col-position">
            <el-form-item label>
              <el-button
                class="commonBut saveBtn"
                @click="toSaveRule"
                :loading="isAdd"
                v-show="isShowSave"
                >保存</el-button
              >
              <el-button class="commonBut" @click="toGoBack">取消</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'addProjectRight',
  data() {
    var checkUserPassword = (rule, value, callback) => {
      var that = this
      var reg = /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]a-zA-Z0-9]{6,18}$/
      if (!reg.test(value)) {
        if (that.type == 'edit') {
          if (that.oldPassword == that.formData.password) {
            callback()
          } else {
            callback('密码仅支持6-18位数字、字母、符号')
          }
        } else {
          callback('密码仅支持6-18位数字、字母、符号')
        }
      } else {
        callback()
      }
    }
    var checkUserProjects = (rule, value, callback) => {
      this.$nextTick(function () {
        if ($('#choiceNameBox').find('li').length < 1) {
          return callback(new Error('请选择所管辖项目'))
        } else {
          callback()
        }
      })
    }
    return {
      loginType: '',
      show: false,
      back: true,
      titleText: '',
      ownerShip: '1',
      unitArr: [], //参建单位列表
      formData: {
        id: '',
        username: '',
        password: '',
        nickname: '',
        tel: '',
        enabled: '',
        roleCode: '',
        userProjectJson: '',
        uscc: '', //参建单位uscc
      },
      //验证
      formRules: {
        nickname: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur',
          },
          {
            min: 2,
            max: 20,
            message: '请输入正确的姓名',
            trigger: 'blur',
          },
        ],
        tel: [
          {
            required: true,
            pattern: /^1[3456789]\d{9}$/,
            message: '手机号格式错误',
            trigger: 'blur',
          },
        ],
        username: [
          {
            required: true,
            message: '用户名为6-18位字母、数字、下划线_组合，不能是纯数字',
            pattern: /^(?![0-9]+$)[0-9a-zA-Z_]{6,18}$/,
            // pattern: /^[a-zA-Z0-9]{6,18}$/,^[a-zA-Z0-9]{6,10}$
            trigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            validator: checkUserPassword,
            // message: "密码仅支持6-18位数字、字母、符号",
            // pattern: /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]a-zA-Z0-9]{6,18}$/,
            trigger: 'blur',
          },
        ],
        // deptmentName: [
        //   {
        //     required: true,
        //     message: "请输入部门名称",
        //     trigger: "blur"
        //   },
        //   {
        //     min: 1,
        //     max: 50,
        //     message: '最长允许输入32个字',
        //     trigger: 'blur'
        //   }
        // ],
        enabled: [
          {
            required: true,
            // validator: checkArea,
            message: '请选择账号状态',
            trigger: 'change',
          },
        ],
        roleCode: [
          {
            required: true,
            message: '请选择岗位',
            trigger: 'change',
          },
        ],
        uscc: [
          {
            required: true,
            message: '请选择参建单位',
            trigger: 'change',
          },
        ],
        userProjectJson: [
          {
            required: true,
            // validator: checkUserProjects,
            // pattern: /^[\s\S]*.*[^\s][\s\S]*$/,
            message: '请选择要授权的管辖项目',
            trigger: 'blur',
          },
        ],
      },
      projectList: [],
      pageSizeNumber: 20,
      total: 0,
      pageNo: 1,
      defaultProps: {
        children: 'children',
        label: 'projectName',
      },
      choiceName: [],
      // 弹窗
      formVisible: false,
      expandOnClick: false,
      map: '',
      selectedprojectList: [],
      //编辑，之前的打卡点id
      id: '',
      type: '',
      isAdd: false,
      enabledData: [
        {
          code: '1',
          name: '正常',
        },
        {
          code: '0',
          name: '禁用',
        },
      ],
      roleList: '',
      editType: '',
      oldPassword: '',
      isShowSave: '',
      proApp: '',
      proAppChecked: false,
    }
  },

  computed: {
    filterRoleList() {
      let filterRoleArr = null
      if (this.roleList.length > 0) {
        if (this.ownerShip == '1' || this.$store.state.userType === 'COMPANY') {
          filterRoleArr = this.roleList.filter(
            (v) =>
              v.code == 'PROJECT_MANAGER' || v.code == 'LABOR_ADMINISTRATOR'
          )
          // filterRoleArr.forEach(v=>{
          //     if(v.code=='PROJECT_MANAGER'){
          //         v.code = "PROJECT_ADMINISTRATOR";
          //     }
          // });
        } else {
          filterRoleArr = this.roleList.filter(
            (v) => v.code == 'FENBAO_MANAGER'
          )
        }
        return filterRoleArr
      } else {
        return []
      }
    },
  },
  async created() {
    this.id = this.$route.query.id
    this.type = this.$route.query.type
    await this.getRemark()
    this.getProApp()
    if (this.$store.state.userType === 'COMPANY') {
      this.loginType = 'company'
      this.getprojectList()
    }
    if (this.type == 'edit') {
      this.titleText = '编辑账号'
      this.formData.id = this.id
      this.getDetail()
      this.editType = 'password'
      // this.getRuleList();
    } else {
      this.titleText = '新增账号'
      this.editType = 'text'
    }
    this.isShowSave =
      this.$store.state.buttonLimitsArr.indexOf('projectAuth:add') > -1 ||
      this.$store.state.buttonLimitsArr.indexOf('projectAuth:update') > -1 ||
      this.$store.state.buttonLimitsArr.indexOf('projectAuthSGF:add') > -1 ||
      this.$store.state.buttonLimitsArr.indexOf('projectAuthSGF:update') > -1 ||
      this.$store.state.buttonLimitsArr.indexOf('projectAuthSGF:add') > -1 ||
      this.$store.state.buttonLimitsArr.indexOf('projectAuthSGF:update') > -1 ||
      this.$store.state.buttonLimitsArr.indexOf('projectUserList:add') > -1 ||
      this.$store.state.buttonLimitsArr.indexOf('projectUserList:update') > -1
  },

  methods: {
    // 更改归属公司
    changeOwner(val) {
      if (this.ownerShip == '2') {
        this.getBulidCompanyList()
        console.log('change')
      }
    },
    // 获取参建列表
    getBulidCompanyList() {
      return this.axios({
        method: 'post',
        url: 'api-p/projectcompany/expand/findprojectcompanylist',
        data: {
          projectId: this.$route.query.projectId,
          type: '10',
        },
      })
        .then((response) => {
          if (response.data.hasError) {
            this.$message.error(response.data.errorMsg)
          } else {
            const results = response.data.result
            this.unitArr = results
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // // 切换参建单位
    // changeBulidCompany(val) {
    //     this.formData.uscc = val;
    // },
    handleNodeClick(item) {
      var index = this.choiceName.length
      var dom = 'department' + index

      //  this.$nextTick(function() {
      //    Velocity($("#"+dom), { opacity: 1, fontSize: '1.3em' }, { duration: 300 })
      //    Velocity($("#"+dom), { opacity: 1, fontSize: '1em' }, { duration: 300 })
      // });

      // console.log(item)

      var list = $('#choiceNameBox').find('li')
      var data = []
      for (var i = 0; i < list.length; i++) {
        data.push($(list[i]).attr('selectedVal'))
      }

      var index = data.indexOf(item.projectId)

      if (index == -1) {
        this.choiceName.push({
          projectName: item.projectName,
          projectId: item.projectId,
        })
        this.$refs.formData.validateField('department')
        // this.selectedprojectList.push(data.value);
        // this.selectedprojectList = this.choiceName;
      }
    },
    //删除选中部门
    toDel(e, item, index) {
      var that = this
      var dom = 'department' + index

      // Velocity( $("#"+dom), { translateX: '15px', rotateZ: '50deg' , width: '120px'}, { duration: 600 })
      // Velocity( $("#"+dom).find(".name"), { translateX: '15px', rotateZ: '50deg' , width: '50px'}, { duration: 200 })

      // Velocity( $("#"+dom), { rotateZ: '100deg' }, { loop: 2 })
      // Velocity( $("#"+dom), {
      //   rotateZ: '45deg',
      //   translateY: '30px',
      //   translateX: '30px',
      //   opacity: 0
      // })

      var that = this
      // setTimeout(function(){
      // $("#choiceNameBox").find("#"+dom).remove();
      this.choiceName.splice(index, 1)
      that.$refs.formData.validateField('department')
      // },3000)
    },
    closeDialog() {},
    toSaveRule() {
      // return
      this.isAdd = true

      // var list = $("#choiceNameBox").find('li');
      // this.selectedprojectList = [];
      // for(var i = 0 ; i <　list.length ; i ++){
      //     this.selectedprojectList.push({orgId:$(list[i]).attr("selectedVal"),type:1})
      // }

      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.saveRule()
        } else {
          this.isAdd = false
        }
      })
    },
    saveRule() {
      // var container = [];
      //   container[0] = this.addressFormData;

      // var data = {
      //   name:this.formData.ruleName,
      //   attendancePoints:JSON.stringify(container),
      //   attendanceOrgs:JSON.stringify(this.selectedprojectList)
      // }
      // console.log(data)
      // this.formData.userProjectJson =  JSON.stringify(this.choiceName);
      // if(this.proAppChecked) {
      //     this.formData.roleCode = this.formData.roleCode + "," + this.proApp;
      // }
      if (this.loginType != 'company') {
        this.choiceName[0] = {
          projectName: this.$route.query.projectName,
          projectId: this.$route.query.projectId,
        }
      }
      let data = {
        id: this.formData.id,
        username: this.formData.username,
        password: this.formData.password,
        nickname: this.formData.nickname,
        tel: this.formData.tel,
        enabled: this.formData.enabled,
        roleCode: this.formData.roleCode,
        userProjectJson: JSON.stringify(this.choiceName),
        uscc: this.formData.uscc,
      }
      var url = ''
      if (this.type == 'edit') {
        // data.id = this.id;
        url = 'api-u/users/update/subaccount'
      } else {
        url = 'api-u/users/add/subaccount'
      }
      this.axios({
        method: 'post',
        url: url,
        data: data,
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              var text = this.type == 'edit' ? '编辑成功' : '添加成功'
              this.$message({
                message: text,
                type: 'success',
              })
              this.goBack('change')
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
            this.isAdd = false
          },
          (response) => {
            this.isAdd = false
          }
        )
        .catch((error) => {
          this.isAdd = false
        })
    },
    //获取项目
    getprojectList(val) {
      this.axios({
        method: 'post',
        url: 'api-p/projectcompany/expand/relatedproject',
        data: {
          projectName: val,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.projectList = response.data.result
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    //获取之前的打卡规则
    getDetail() {
      var data = {
        id: this.id,
      }
      return this.axios({
        method: 'post',
        url: 'api-u/users/subaccount/detail',
        data: data,
      })
        .then(
          async (response) => {
            if (!response.data.hasError) {
              this.formData.id = response.data.result.id
              this.formData.username = response.data.result.username
              this.formData.password = response.data.result.password
              this.formData.nickname = response.data.result.nickname
              this.formData.tel = response.data.result.tel
              this.formData.enabled = response.data.result.enabled
              this.formData.roleCode = response.data.result.roleCode
              this.oldPassword = this.formData.password
              if (
                response.data.result.userProjects &&
                response.data.result.userProjects.length > 0
              ) {
                let project = response.data.result.userProjects
                this.formData.userProjectJson = project[0].projectId
                this.choiceName[0] = {
                  projectName: project[0].projectName,
                  projectId: project[0].projectId,
                }
              }
              var roles = response.data.result.roles
              for (var i = 0; i < roles.length; i++) {
                var code = roles[i].code
                if (code === 'PROJECT_APPLICATION') {
                  this.proAppChecked = true
                }
              }
              if (response.data.result.companyName) {
                await this.getBulidCompanyList()
                this.formData.uscc = response.data.result.uscc
                this.ownerShip = '2'
              }
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    toGoBack() {
      this.goBack()
    },
    getRemark() {
      var data = {
        id: this.id,
      }
      return this.axios({
        method: 'post',
        url: 'api-u/role/description',
        // data:data
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.roleList = response.data.result
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    getProApp() {
      this.axios({
        method: 'post',
        url: 'api-u/role/proapp',
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.proApp = response.data.result[0].code
          }
        })
        .catch((error) => {})
    },
    radioChange(val) {
      if (val === 'PROJECT_MANAGER') {
        this.proAppChecked = true
      } else {
        this.proAppChecked = false
      }
    },
    goBack(type) {
      var way = ''
      if (type == 'change') {
        way = 'CHANGE_SLIDER_NAME'
      } else {
        way = 'GOBACK_NAME'
      }
      if (this.type == 'edit') {
        let pathObj = {
          path: '/home/projectRight/projectRightDetail',
          name: 'projectRightDetail',
          query: {
            id: this.id,
          },
        }
        if (this.loginType != 'company') {
          pathObj.query.projectId = this.$route.query.projectId
          pathObj.query.projectName = this.$route.query.projectName
        }
        // this.$router.push("/home/projectRight/projectRightDetail");
        this.$router.push(pathObj)
        this.$store.commit(way, {
          oldUrl: '/home/projectRight/projectRightList',
          newUrl: this.$router.currentRoute.fullPath,
        })
      } else {
        this.$router.push('/home/projectRight/projectRightList')
        this.$store.commit(way, {
          oldUrl: '/home/projectRight/projectRightList',
          newUrl: this.$router.currentRoute.fullPath,
        })
      }
    },
    selectValue(id) {
      let selectValue = {}
      selectValue = this.projectList.find((item) => {
        return item.projectId === id
      })
      this.choiceName[0] = {
        projectName: selectValue.projectName,
        projectId: selectValue.projectId,
      }
    },
  },
}
</script>

<style scoped lang="less">
.department {
  transform-origin: left;
  height: 40px !important;
  padding-right: 12px !important;
  .icon {
    color: #009588;
    font-size: 14px;
    vertical-align: middle;
    float: left;
    margin-right: 5px;
  }
  .name {
    // float: left;
    transform-origin: left;
    display: inline-block;
    font-style: normal;
    width: 245px;
    overflow: hidden; /*超出的部分隐藏起来。*/
    white-space: nowrap; /*不显示的地方用省略号...代替*/
    text-overflow: ellipsis; /* 支持 IE */
  }
  .del {
    transform-origin: left;
    color: #51aeff !important;
  }
}

// .row-padding-bottom {
//   margin-bottom: 10px;
// }

.mainCon {
  height: calc(100% - 50px);
  padding: 40px 0px;
  overflow-y: auto;
  //   /deep/ .el-form{
  //     padding: 50px 60px;
  //     .el-input__inner{
  //       width: 340px;
  //     }
  //   }
  .treeBox {
    width: 666px;
    // width: 200px;
    background: #f5f7fa;
    border: 1px solid #dee5f4;
    border-radius: 4px;
    padding: 12px 0px 12px 16px;
    .tree {
      // padding:22px;
      height: 235px;
      overflow: auto;
      border-right: 1px solid #dee5f4;
      padding-right: 12px;
      p {
        font-size: 14px;
        line-height: 36px;
        color: #999;
        border-bottom: 1px solid #dee5f4;
      }
      .el-tree {
        background: #f5f7fa;
        /deep/ .el-tree-node__label {
          overflow: hidden;
          text-overflow: ellipsis; /* 超出部分显示省略号 */
          white-space: nowrap; /*规定段落中的文本不进行换行 */
        }
      }
    }
    .selectedDepartment {
      padding: 12px;
      margin-top: -12px;
      padding-right: 0;
      height: 261px;
      overflow: auto;
      p {
        font-size: 14px;
        line-height: 36px;
        color: #999;
        border-bottom: 1px solid #dee5f4;
      }
      .del {
        font-size: 14px;
        color: #0070f5;
        cursor: pointer;
      }
    }
  }

  .addressNameInfo {
    line-height: 28px;
    width: 666px;
    i {
      font-size: 18px;
      color: #009588;
      vertical-align: middle;
    }
    .range {
      color: #999;
    }
  }
}

#choiceNameBox li {
  line-height: 40px;
  height: 40px !important;
  padding-right: 12px;
}
.AuthBox {
  height: calc(235px - 37px) !important;
  overflow: auto;
}
@media screen and (max-width: 1280px) {
  // 	.mainCon .el-form{
  //     padding:50px 20px;
  //   }

  .mainCon .treeBox {
    width: 630px;
  }

  .department .name {
    width: 220px;
  }

  #l-map {
    height: 200px !important;
  }
}

@media all and (min-width: 1360px) and (max-width: 1470px) {
  #l-map {
    height: 235px !important;
  }
}
</style>
<style>
.col-position-tree .el-tree-node__label {
  margin-left: -25px;
}
.col-position-tree .el-tree-node__content {
  height: 40px;
  line-height: 40px;
}
</style>
